package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UserLocationServiceImpl implements UserLocationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Double longitude, Double latitude, String addrStr, Long userId) {
        Query query = new Query(
                Criteria.where("userId").is(userId)
        );
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation == null) {
            userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        } else {
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(addrStr);
            userLocation.setLastUpdated(userLocation.getUpdated());
            userLocation.setUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);
        }
    }
    //搜附近
    @Override
    public List<Long> searchNearUserId(Long userId, Long distance) {

        Query queryUser = new Query(
                Criteria.where("userId").is(userId)
        );
        GeoJsonPoint location = mongoTemplate.findOne(queryUser, UserLocation.class).getLocation();

        Distance dis = new Distance(distance / 1000, Metrics.KILOMETERS);

        Circle circle = new Circle(location, dis);

        Query query = new Query(
                Criteria.where("location").withinSphere(circle)
        );
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);
        List<Long> nearUserIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userLocations)) {
            for (UserLocation userLocation : userLocations) {
                nearUserIdList.add(userLocation.getUserId());
            }
        }
        return nearUserIdList;
    }
}
